package lch.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import lch.constant.MessageConstant;
import lch.constant.RedisMessageConstant;
import lch.entity.Result;
import lch.pojo.Member;
import lch.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author lch
 * @date 2019-12-25 11:49
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse httpServletResponse) {
        String telephone = (String) map.get("telephone");//获取手机号
        String validateCode = (String) map.get("validateCode");//获取输入的验证码
        String validateCodeByRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);//获取存取的验证码
        if (validateCode != null && validateCodeByRedis != null && validateCodeByRedis.equals(validateCode)) {
            //通过手机号查找会员
            Member member = memberService.findByTelephone(telephone);
            //不是会员
            if (member == null) {
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                //注册并添加
                memberService.add(member);
            }
            //存储手机号到cookie
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");
            //设置存储时长，将手机号作为会员凭证存储30天
            cookie.setMaxAge(60 * 60 * 24 * 30);
            httpServletResponse.addCookie(cookie);
            //将用户信息转成JSON字符串形式
            String string = JSON.toJSON(member).toString();
            //存储用户信息，时长30分钟
            jedisPool.getResource().setex(telephone, 1800, string);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
